package com.soap.desensitize.posterity.json;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.soap.desensitize.exception.strategy.DecodeException;
import com.soap.desensitize.exception.strategy.EncodeException;
import com.soap.desensitize.posterity.AbstractPosterity;
import com.soap.desensitize.posterity.entity.EntityDesensitization;
import com.soap.desensitize.strategy.rreversible.symmetry.DesStrategy;

import java.io.IOException;

/**
 * @desc 对象转json脱敏子孙后代类
 */
public class ObjcetToJsonPosterity extends AbstractJsonPosterity{
    private ObjectMapper mapper=new ObjectMapper();
    /**
     * @desc 有参构造器
     */
    private ObjcetToJsonPosterity() {
        super(DesStrategy.getInstance());
    }

    private static ObjcetToJsonPosterity instance = null;
    /**
     * @desc 获得实例
     * @return
     */
    public static synchronized ObjcetToJsonPosterity getInstance(){
        if(instance == null){
            instance = new ObjcetToJsonPosterity();
        }
        return instance;
    }
    @Override
    public String encode(Object data) throws EncodeException {
        AbstractPosterity entiryDesensitization = EntityDesensitization.getInstance(getEncry());
        Object encodeValue = entiryDesensitization.judgeAndEncode(encry);
        System.out.println(encodeValue);
        String json=null;
        try {
            json=new ObjectMapper().writeValueAsString(encodeValue);
            return json;
        } catch (IOException e) {
            throw new EncodeException("json序列化异常"+e.getMessage());
        }
    }
    @Override
    public Object decode(String data,Class cla) throws DecodeException {
        AbstractPosterity entiryDesensitization = EntityDesensitization.getInstance(getEncry());
        try {
            Object object=mapper.readValue(data,cla);
            System.out.println("序列话前："+data);
            System.out.println("反序列化后："+object);
            Object decodeObject = entiryDesensitization.judgeAndDecode(encry);
            return decodeObject;
        } catch (IOException e) {
            throw new DecodeException("Json 反序列化异常 "+e.getMessage());
        }
    }

}
